package redis

import (
	"context"
	"github.com/go-redis/redis/v8"
	"gogame/gameconfig"
	"gogame/lib/database/redis/cluster"
	"gogame/lib/database/redis/single"
)

type RedisStruct struct {
	ctx      context.Context
	Options  gameconfig.Redis // redis配置
	Client   redis.Cmdable    // redis client
	Pipeline *Pipeline        // redis 管道c
	Ver      string           // 本服还是跨服
}

func NewRedisStruct(ver string) *RedisStruct {
	options := InitOptions(ver)

	var _client redis.Cmdable
	switch options.IsCluster {
	// 单机
	case false:
		_client = single.NewSingleClient(options)

	// 集群
	case true:
		_client = cluster.NewClusterClient(options)

	}
	_redis := &RedisStruct{
		ctx:      context.Background(),
		Options:  options,
		Client:   _client,
		Pipeline: NewPipeline(_client, ver),
		Ver:      ver,
	}

	return _redis

}

var Redis *RedisStruct
var CrossRedis *RedisStruct

// InitRedis 初始化redis
func initRedis(ver string) *RedisStruct {
	switch ver {
	case "cross":
		if CrossRedis != nil {
			return CrossRedis
		}
	default:
		if Redis != nil {
			return Redis
		}
	}

	_redis := NewRedisStruct(ver)

	// 这里是因为某个redis节点连接时很慢，后续可以去掉go
	go func() {
		_redis.Client.Ping(_redis.Context())
	}()

	switch ver {
	case "cross":
		CrossRedis = _redis
	default:
		Redis = _redis
	}

	return _redis
}

// InitRedis 初始化redis
func InitRedis() *RedisStruct {
	return initRedis("")
}

// InitCrossRedis 初始化跨服redis
func InitCrossRedis() *RedisStruct {
	return initRedis("cross")
}

func (r *RedisStruct) Context() context.Context {
	return r.ctx
}

// FlushAll 清除所有key 阻塞
func (r *RedisStruct) FlushAll() {
	r.Client.FlushAll(r.Context())
}

// FlushAllAsync 清除所有key 非阻塞
func (r *RedisStruct) FlushAllAsync() {
	r.Client.FlushAllAsync(r.Context())
}
